package com.wteam.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wteam.PoJo.DO.Goods;
import com.wteam.PoJo.DO.Params;
import com.wteam.PoJo.VO.GoodsVO;
import com.wteam.PoJo.VO.ParamsVO;
import com.wteam.mapper.ParamsMapper;
import com.wteam.Service.IParamsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wteam.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品参数表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-16
 */
@Service
public class ParamsServiceImpl extends ServiceImpl<ParamsMapper, Params> implements IParamsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<ParamsVO> selectparams(Long id) {
        String redis = id.toString();
        String key = "GoodParams";
        //查缓存
        ParamsVO paramsVO1 = (ParamsVO) redisTemplate.opsForHash().get(key, redis);


        if (BeanUtil.isNotEmpty(paramsVO1)) {
            return Result.success(paramsVO1);
        }
        Goods one = Db.lambdaQuery(Goods.class).eq(Goods::getId, id).one();

        Params byId = lambdaQuery().eq(Params::getGoodsId, id).eq(Params::getType, 1).one();

      if (BeanUtil.isEmpty(byId)){
          ParamsVO paramsVO = BeanUtil.copyProperties(one, ParamsVO.class);
          paramsVO.setGoodsId(id);
          return Result.success(paramsVO);
      }
        ParamsVO paramsVO = BeanUtil.copyProperties(byId, ParamsVO.class);
        BeanUtil.copyProperties(one, paramsVO);
        //缓存
        redisTemplate.opsForHash().put(key, redis, paramsVO);

        return Result.success(paramsVO);
    }

    @Override
    public Result<List<ParamsVO>> selectgoods(List<Long> ids) {

        List<Goods> list = Db.lambdaQuery(Goods.class).in(Goods::getId, ids).list();
        Map<Long, Goods> collect = list.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));

        List<Params> byId = lambdaQuery().in(Params::getGoodsId, ids).eq(Params::getType, 1).list();
        List<ParamsVO> paramsVOS = BeanUtil.copyToList(byId, ParamsVO.class);
        if (CollUtil.isEmpty(paramsVOS)){
            List<GoodsVO> goodsVOS = BeanUtil.copyToList(list, GoodsVO.class);
            System.out.println(goodsVOS.toString());
            return Result.success(goodsVOS);
        }
        for (ParamsVO paramsVO : paramsVOS) {
            Goods goods = collect.get(paramsVO.getGoodsId());
            BeanUtil.copyProperties(goods,paramsVO);
        }
        return Result.success(paramsVOS);
    }
}
